import {NotificationStore} from '../components/NotificationPlugin/index'
import swal from 'sweetalert2'
import moment from 'moment-timezone'
import momentDurationFormatSetup from 'moment-duration-format'

momentDurationFormatSetup(moment)

export const cache = (key, val)=>{
  if (key === 'clear') {
    window.localStorage.clear();
  } else if (val === null) {
    window.localStorage.removeItem(key);
  } else if (val) {
    window.localStorage[key] = val;
  } else {
    return window.localStorage[key];
  }
}

export function validateUrl(url){
  return /^(http|https):\/\/.+$/.test(url)
}

export function validateEmail(email){
  return /^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)+$/.test(email);
}

// timeZone: Asia/Shanghai
export const formatDate = (value, formatStr = 1, timeZone='') => {
  if(!value){
    return '';
  }

  let date = moment(value);
  if(timeZone===true){
    timeZone = 'Asia/Shanghai';
  }
  if(timeZone){
    date = date.tz(timeZone);
  }

  let targetFormatStr = formatStr;
  if(targetFormatStr === 1){
    targetFormatStr = 'YYYY-MM-DD HH:mm:ss'
  }else if(targetFormatStr === 2){
    targetFormatStr = 'YYYY-MM-DD'
  }

  if (date.isValid()) {
    return date.format(targetFormatStr);
  }
  return '';
};

export const formatAge = (startDate, endDate)=>{
  const typeStart = Object.prototype.toString.call(startDate);
  const typeEnd = Object.prototype.toString.call(endDate);
  if(typeStart!=="[object Date]" || typeEnd !== "[object Date]"){
    return '';
  }

  const milliseconds = new Date(endDate) - new Date(startDate);
  return moment.duration(milliseconds, 'milliseconds').format('y[岁]M[个月]')
}

// type: info, success, warning, danger
export const toast = (msg, type='success', icon='notifications')=>{
  if(type==='error'){
    type='danger';
  }
  NotificationStore.notify({
    message: msg,
    icon: icon,
    verticalAlign: 'top',
    horizontalAlign: 'center',
    type: type,
  })
}

// type: warning, error, success, info question
export const alert = (msg, type = 'success', title='')=>{
  return new Promise((resolve)=>{
    swal.fire({
      title: title,
      text: msg,
      type: type,
      buttonsStyling: false,
      confirmButtonText: '确定',
      confirmButtonClass: 'md-button md-success',
    }).then(()=>{
      resolve()
    })
  })
}

// type: warning, error, success, info question
export const confirm = (msg, type = 'question', title='', okText='确定', cancelText='取消')=>{
  return new Promise((resolve, reject)=>{
    swal.fire({
      title: title,
      text: msg,
      type: type,
      buttonsStyling: false,
      showCancelButton: true,
      confirmButtonText: okText,
      cancelButtonText: cancelText,
      confirmButtonClass: 'md-button md-success',
      cancelButtonClass: 'md-button md-danger',
    }).then(result=>{
      if(result.value){
        resolve();
      }else{
        reject();
      }
    })
  })
}
